package com.kevin.controller.controller;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.pinyin.PinyinUtil;
import cn.hutool.extra.servlet.ServletUtil;
import com.alibaba.fastjson.JSONObject;
import com.kevin.common.api.R;
import com.kevin.service.forest.RollApi;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.ihxq.projects.pna.PhoneNumberLookup;
import net.dreamlu.mica.ip2region.core.Ip2regionSearcher;
import net.dreamlu.mica.ip2region.core.IpInfo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * 测试controller
 *
 * @author wh
 * @date 2023-12-19 14:22
 */
@Slf4j
@RestController
@RequestMapping("test")
@Api(tags = "测试管理")
@RequiredArgsConstructor
public class TestController {
    private final RollApi rollApi;
    private final Ip2regionSearcher ip2regionSearcher;

    @GetMapping(value = "ip")
    @ApiOperation(value = "ip查询")
    public R<IpInfo> sendNewMsg(String ip, HttpServletRequest request) {
        if (StrUtil.isEmpty(ip)) {
            String clientIP = ServletUtil.getClientIP(request);
            if ("0:0:0:0:0:0:0:1".equals(clientIP)) {
                clientIP = "127.0.0.1";
            }
            ip = clientIP;
        }
        return R.ok(ip2regionSearcher.memorySearch(ip));
    }

    @GetMapping(value = "pinyin")
    @ApiOperation(value = "拼音查询")
    public R<String> pinyin(@RequestParam String text) {
        return R.ok(PinyinUtil.getPinyin(text));
    }

    @GetMapping(value = "phone")
    @ApiOperation(value = "手机号归属地查询")
    public R<?> mobile(@RequestParam String phone) {
        PhoneNumberLookup lookup = new PhoneNumberLookup();
        return R.ok(lookup.lookup(phone).orElse(null));
    }

    @GetMapping(value = "douyin")
    @ApiOperation(value = "抖音视频解析")
    public R<?> douyin(@RequestParam String url) {
        return R.ok(DyUtil.analyze(url));
    }

    @GetMapping(value = "video")
    @ApiOperation(value = "视频解析")
    public R<?> video(@RequestParam String url) {
        JSONObject analyze = DyUtil.analyze(url);
        log.info("抖音结果:\n{}", analyze);
        JSONObject item = analyze.getJSONArray("item_list").getJSONObject(0);
        return R.ok(PlatformVO.builder()
                .title(item.getString("desc"))
                .desc(item.getString("desc"))
                .urlList(item.getJSONObject("video").getJSONObject("play_addr").getJSONArray("url_list").toJavaList(String.class))
                .coverList(item.getJSONObject("video").getJSONObject("cover").getJSONArray("url_list").toJavaList(String.class))
                .build());
    }

}
